/**
 * Created with IntelliJ IDEA
 * Description:
 * User: Administrator
 * Data: 2023 - 09 - 12
 * Time: 14:29
 */
//有三个线程，线程名称分别为：a，b，c。每个线程打印自己的名称。需要让他们同时启动，并按 c，b，a的顺序打印
public class Demo5 {
    static Object lock1 = new Object();
    static Object lock2 = new Object();
    static Object lock3 = new Object();
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
             synchronized (lock1) {
                 try {
                     lock1.wait();
                 } catch (InterruptedException e) {
                     throw new RuntimeException(e);
                 }
                 System.out.print(Thread.currentThread().getName());
             }
        }, "a");
        Thread t2 = new Thread(() -> {
            synchronized (lock2) {
                try {
                    lock2.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.print(Thread.currentThread().getName());
                synchronized (lock1) {
                    lock1.notify();
                }
            }
        }, "b");
        Thread t3 = new Thread(() -> {
            synchronized (lock3) {
                try {
                    lock3.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.print(Thread.currentThread().getName());
                synchronized (lock2) {
                    lock2.notify();
                }
            }
        }, "c");
        t1.start();
        t2.start();
        t3.start();
        Thread.sleep(1000);//这里的sleep很重要，因为要确保t1、t2、t3都拿到了锁并进入wait()状态
        synchronized (lock3) {
            lock3.notify();
        }
    }
}
